<template>
  <div class="language-select interactive" :class="{ active: showDropdown }">
    <div class="language-select-value click" @click="showDropdownModal">
      <icon size="8px" class="mr-4" name="ic_arrow_down" />
      <p>{{ languageObj.label }}</p>
    </div>
    <div v-if="showDropdown" class="language-select-dropdown">
      <div
        v-for="item in LANGUAGES"
        :key="item.value"
        class="language-select-dropdown-option click cursor-pointer"
        :class="{ active: language === item.value }"
        @click="selectLanguage(item)"
      >
        {{ item.label }}
      </div>
    </div>
  </div>
</template>

<script>
import { LANGUAGES } from '@/constants/index';

export default {
  data() {
    return {
      LANGUAGES,
      showDropdown: false
    };
  },

  computed: {
    language() {
      return this.$store.state.app.language;
    },
    languageObj() {
      const { language } = this;
      const item = LANGUAGES.find(t => t.value === language);
      return item || {};
    }
  },

  beforeDestroy() {
    this.removeListener();
  },

  methods: {
    selectLanguage(item) {
      if (item.value === this.language) return;
      this.$store.dispatch('app/updateLanguage', item.value);
      this.showDropdown = false;
      this.removeListener();
      setTimeout(() => {
        this.$router.push({
          path: this.localePath('/', this.$i18n.locale)
        });
      }, 100);
    },

    showDropdownModal() {
      document.addEventListener('click', this.registerListener);
      this.showDropdown = true;
    },

    registerListener(e) {
      if (!this.$el.contains(e.target)) {
        this.showDropdown = false;
        this.removeListener();
      }
    },

    removeListener() {
      document.removeEventListener('click', this.registerListener);
    }
  }
};
</script>

<style lang="scss" scoped>
.language-select {
  position: relative;
}
.language-select-value {
  display: flex;
  align-items: center;
  height: 32px;
  padding: 0 12px;
  font-size: 14px;
  color: #0c0c1c;
}

.language-select-dropdown {
  width: 116px;
  position: absolute;
  bottom: -4px;
  right: 0;
  transform: translateY(100%);
  background: #ffffff;
  box-shadow: 0 1px 8px 0 rgba(12, 12, 28, 0.04);
  border-radius: 8px;
  z-index: 1;

  &-option {
    height: 36px;
    padding: 0 16px;
    white-space: nowrap;
    border-radius: 8px;
    font-size: 14px;
    color: #0c0c1c;
    background: rgba(12, 12, 28, 0);
    border-radius: 4px;
    line-height: 36px;
    text-align: center;
    &.active {
      &,
      &:hover {
        background: rgba(12, 12, 28, 0);
        border-radius: 4px;
        color: #fd4b49;
      }
    }
  }
}
</style>
